package me.flyray.crm.core.feignserver;


import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.crm.core.config.WxMpConfiguration;
import me.flyray.crm.facade.feignclient.modules.wechat.WxAuthServiceClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: bolei
 * @date: 16:01 2019/2/11
 * @Description: 微信授权服务
 */

@Controller
@Slf4j
public class WxAuthServiceClientFeign implements WxAuthServiceClient {

    @Override
    @ResponseBody
    public BaseApiResponse<WxMpUser> wxAuth(@RequestParam("appId") String appId, @RequestParam("code") String code, @RequestParam("scope") String scope){

        log.info("微信授权服务请求开始");
        WxMpService mpService = WxMpConfiguration.getMpServices().get(appId);
        WxMpUser user = new WxMpUser();
        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            log.info("微信授权服务请求返回token{}",accessToken);
            if ("snsapi_userinfo".equals(scope)){
                user = mpService.oauth2getUserInfo(accessToken, null);
            }
            user.setOpenId(accessToken.getOpenId());
        } catch (WxErrorException e) {
            e.printStackTrace();
            return BaseApiResponse.newFailure(e.getLocalizedMessage(),e.getMessage());
        }
        log.info("微信授权服务请求返回成功");
        return BaseApiResponse.newSuccess(user);
    }

}
